package com.mhs.dataclassification;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.mhs.mhs_gui.R;
import com.mhs.mydialog.MyDialogListner;

import com.mhs.BUS.BenhVienBUS;
import com.mhs.BUS.ThuocBUS;
import com.mhs.DTO.BenhVienDTO;
import com.mhs.DTO.MySQLiteHelper;
import com.mhs.DTO.ThuocDTO;
import com.mhs.dataclassification.processA.ProcessAi;
import com.mhs.dataclassification.processA.Process_ai;
import com.mhs.dataclassification.processTS.ProcessTS_BenhVienDTO;
import com.mhs.dataclassification.processTS.ProcessTS_ThuocDTO;
import com.mhs.dataclassification.processUtility.ProcessUtility;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Classification extends Activity {
	MySQLiteHelper dbHelper;
	ListView listViewSettings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		listViewSettings = (ListView) findViewById(R.id.listViewMenuSettings);
	}

	@Override
	protected void onStart() {
		try {
			super.onStart();
			dbHelper = new MySQLiteHelper(this);
			ArrayList<String> lstItem = new ArrayList<String>();
			lstItem.add("Classify");
			lstItem.add("Check free space");
			lstItem.add("Clear All Cache");
			String[] sItem = lstItem.toArray(new String[0]);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, sItem);
			listViewSettings.setAdapter(adapter);
			listViewSettings.setOnItemClickListener(listener);
		} catch (Exception ex) {
			MyDialogListner.ShowMessageAlert(this, ex.toString());
		}
	}

	OnItemClickListener listener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:
				// Classify ThuocDTO:
				classifyEntity("thuoc");
				classifyEntity("benhvien");
				Toast.makeText(getApplicationContext(), "Classified",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				checkFreeSpace();
				break;
			case 2:
				try {
					List<Integer> lstIdToDel = classifyEntity("thuoc");
					if (lstIdToDel != null && lstIdToDel.size() > 0) {
						try {
							clearCache(lstIdToDel, "thuoc");
							Toast.makeText(getApplicationContext(),
									"Cleared Cache", Toast.LENGTH_SHORT).show();
						} catch (Exception ex) {
							Toast.makeText(getApplicationContext(),
									"Cleared Cache Error", Toast.LENGTH_SHORT)
									.show();
						}

					} else {
						Toast.makeText(getApplicationContext(),
								"Không có dữ liệu trong ứng dụng!", Toast.LENGTH_SHORT)
								.show();
					}
				} catch (Exception ex) {
					Toast.makeText(getApplicationContext(),
							"Cleared Cache Error", Toast.LENGTH_SHORT)
							.show();
				}
				try {
					List<Integer> lstIdToDel2 = classifyEntity("benhvien");
					if (lstIdToDel2 != null && lstIdToDel2.size() > 0) {
						try {
							clearCache(lstIdToDel2, "benhvien");
							Toast.makeText(getApplicationContext(),
									"Cleared Cache", Toast.LENGTH_SHORT).show();
						} catch (Exception ex) {

						}
					} else {
						Toast.makeText(getApplicationContext(),
								"Không có dữ liệu trong ứng dụng!", Toast.LENGTH_SHORT)
								.show();
					}
				} catch (Exception ex) {
					Toast.makeText(getApplicationContext(),
							"Cleared Cache Error", Toast.LENGTH_SHORT)
							.show();
				}

				break;
			}
		}
	};

	@Override
	protected void onResume() {
		// datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		dbHelper.close();
		super.onPause();
	}

	private List<Integer> classifyEntity(String entityName) {
		int Di = 1;
		List<Temp> lstTemp = new ArrayList<Temp>();
		List<Integer> lstIdToDel = new ArrayList<Integer>();
		Entity entity = Entity.valueOf(entityName);
		switch (entity) {
		case thuoc:
			ThuocBUS thuocBUS = new ThuocBUS();
			List<ThuocDTO> lstThuoc = thuocBUS.getAllThuocDTO(this);
			if (lstThuoc != null && lstThuoc.size() != 0) {
				for (int i = 0; i < lstThuoc.size(); i++) {
					ThuocDTO thuoc = lstThuoc.get(i);
					// get tik, K
					Long tik = thuoc.getTS_ThuocDTO();
					int K = thuoc.getK_ThuocDTO();
					// calculate ai
					Long tc = ProcessTS_ThuocDTO.getCurrentTime();
					double ai = Process_ai.calculate_ai(K, tc, tik);
					// add to list<Temp>
					Temp temp = new Temp();
					temp.setMa(thuoc.getMATHUOC_CLIENT());
					temp.setAi(ai);
					temp.setSizei(thuoc.getSize_ThuocDTO());
					temp.setTTLi(thuoc.getTTL_ThuocDTO());
					lstTemp.add(temp);
				}
				// use list<Temp>
				double ak = ProcessAi.calculate_Ak(lstTemp);
				if (lstTemp.size() != 0) {
					for (int j = 0; j < lstTemp.size(); j++) {
						// calculate Ai
						Temp temp = lstTemp.get(j);
						double Ai = ProcessAi.calculate_Ai(ak, temp.getAi());
						// calculate utilityi
						double utilityi = ProcessUtility.calculateUtilityi(Ai,
								Di, temp.getTTLi(), temp.getSizei());
						temp.setUtilityi(utilityi);
					}
				}
				// sort list<Temp> asc utilityi
				Collections.sort(lstTemp, Sorter.COMPARATOR);
				// lstTemp = ProcessUtility.sortListAsc(lstTemp);
				// get top ten Temp.Ma in list<Temp> and save it to clear memory
				boolean flag = true;
				int k = 0;
				while (flag) {
					Temp t = lstTemp.get(k);
					lstIdToDel.add(t.getMa());
					if (k == ((int) (lstTemp.size() * 10 / 100))) {
						flag = false;
					}
					k++;
				}
				break;
			} else {
				MyDialogListner.ShowMessageAlert(this,
						"Không có dữ liệu trong ứng dụng!");
				return null;
			}
		case benhvien:
			BenhVienBUS benhvienBUS = new BenhVienBUS();
			List<BenhVienDTO> lstBenhVien = benhvienBUS.getAllBenhVienDTO(this);
			if (lstBenhVien != null && lstBenhVien.size() != 0) {
				for (int i = 0; i < lstBenhVien.size(); i++) {
					BenhVienDTO benhvien = lstBenhVien.get(i);
					// get tik, K
					Long tik = benhvien.getTS_BenhVienDTO();
					int K = benhvien.getK_BenhVienDTO();
					// calculate ai
					Long tc = ProcessTS_BenhVienDTO.getCurrentTime();
					double ai = Process_ai.calculate_ai(K, tc, tik);
					// add to list<Temp>
					Temp temp = new Temp();
					temp.setMa(benhvien.getMABV_CLIENT());
					temp.setAi(ai);
					temp.setSizei(benhvien.getSize_BenhVienDTO());
					temp.setTTLi(benhvien.getTTL_BenhVienDTO());
					lstTemp.add(temp);
				}
				// use list<Temp>
				double ak = ProcessAi.calculate_Ak(lstTemp);
				if (lstTemp.size() != 0) {
					for (int j = 0; j < lstTemp.size(); j++) {
						// calculate Ai
						Temp temp = lstTemp.get(j);
						double Ai = ProcessAi.calculate_Ai(ak, temp.getAi());
						// calculate utilityi
						double utilityi = ProcessUtility.calculateUtilityi(Ai,
								Di, temp.getTTLi(), temp.getSizei());
						temp.setUtilityi(utilityi);
					}
				}
				// sort list<Temp> asc utilityi
				Collections.sort(lstTemp, Sorter.COMPARATOR);
				// lstTemp = ProcessUtility.sortListAsc(lstTemp);
				// get top ten Temp.Ma in list<Temp> and save it to clear memory
				boolean flag = true;
				int k = 0;
				while (flag) {
					Temp t = lstTemp.get(k);
					lstIdToDel.add(t.getMa());
					if (k == ((int) (lstTemp.size() * 10 / 100))) {
						flag = false;
					}
					k++;
				}
				break;
			} else {
				MyDialogListner.ShowMessageAlert(this,
						"Không có dữ liệu trong ứng dụng!");
				return null;
			}
		case chitiettoathuoc:
			break;
		case nhacnhouongthuoc:
			break;
		case phanloaithuoc:
			break;
		case phieukham:
			break;
		case socuu:
			break;
		case sokhambenh:
			break;
		case thebhyt:
			break;
		default:
			break;
		}
		return lstIdToDel;
	}

	private void checkFreeSpace() {
		long freeSapce = getInternalAvailableSpace();
		if (freeSapce < 195436801) {
			// hien thi thong bao bo nho day
			showDialogFullMemory(this,
					"Dung lượng bộ nhớ đầy, vui lòng xóa bớt các dữ liệu không cần thiết!");
		} else {
			// hien thi thong bao dung luong con lai cua bo nho
			MyDialogListner.ShowMessageAlert(this, "Dung lượng bộ nhớ còn lại "
					+ String.valueOf(freeSapce));
		}
	}

	public static long getInternalAvailableSpace() {
		long availableSpace = -1L;
		try {
			StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
			stat.restat(Environment.getDataDirectory().getPath());
			availableSpace = (long) stat.getAvailableBlocks()
					* (long) stat.getBlockSize();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return availableSpace;
	}

	public void clearCache(List<Integer> lstIdToDel, String entityName) {
		if (lstIdToDel.size() > 0 && lstIdToDel != null) {
			for (int i = 0; i < lstIdToDel.size(); i++) {
				Entity entity = Entity.valueOf(entityName);
				switch (entity) {
				case thuoc:
					// del thuocDTO with
					ThuocBUS thuocBUS = new ThuocBUS();
					boolean checkDelThuoc = thuocBUS.delThuocDTO(
							lstIdToDel.get(i), this);
					if (checkDelThuoc) {
						// do nothing
					} else {
						MyDialogListner.ShowMessageAlert(this, "Error!");
						return;
					}
					break;
				case benhvien:
					// del benhvienDTO with
					BenhVienBUS bvBUS = new BenhVienBUS();
					boolean checkDelBV = bvBUS.delBenhVienDTO(
							lstIdToDel.get(i), this);
					if (checkDelBV) {
						// do nothing
					} else {
						MyDialogListner.ShowMessageAlert(this, "Error!");
						return;
					}
					break;
				}

			}
		} else {
			MyDialogListner.ShowMessageAlert(this, "Lỗi phân loại dữ liệu!");
			return;
		}
	}

	public void showDialogFullMemory(Context con, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(con);
		builder.setTitle("Thông báo MHS");
		builder.setIcon(android.R.drawable.ic_dialog_info);

		builder.setMessage(message);
		builder.setPositiveButton("Auto clear cache ", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				clearCache(classifyEntity("thuoc"), "thuoc");
			}
		});
		builder.setNegativeButton("Cancel", null);
		AlertDialog diag = builder.create();
		diag.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 0, 1, "Sync");
		// menu.add(1, 1, 2, "Settings");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			startService(new Intent(this, com.mhs.sync.Sync.class));
			break;
		case 1:
			Intent classificationIntent = new Intent(this, Classification.class);
			startActivity(classificationIntent);
			break;
		}
		super.onOptionsItemSelected(item);
		return false;
	}
}
